For the following exercises, we will again use data on population from Gapminder.
As per usual, we first need to read in the data. You can just copy, paste and run the following code in(to) your script.
library(readr)
library(dplyr)
gap_pop <- read_csv("../data/gapminder/population_total.csv") %>%
rename(country = "Total population")
Again, the data are currently in wide format.
starts_with(). We also want to keep the country column.
As you may have already noticed, the dataset comprises some missing data points. Before we start analyzing the data, we might want to know for how many countries we have complete data.
drop_na() function from tidyr.
As in the previous set of data wrangling exercises, we now want to transform the data into the long format.
integer.
mutate().
Now let’s apply some of the advanced filtering options we discussed in the Data Wrangling - Part 2 session.
Create two new dataframes that include different subets of the gap_pop data:
Data for all countries for the 1990s (name this one gap_pop_1990s),
Data for all years but only for Germany (name this one gap_pop_ger).
dplyr to create the first new data frame and a specific matching operator to create the second one.
For some comparisons (especially via plots), it might help to know which continent the country is located on. For this purpose, we will create a new continent variable. As it would be quite tedious to create this variable manually for all of the countries in the dataset, we will do this only for a subset in this exercise. Just run the following code in your local script to create this subset.
gap_pop_subset <- gap_pop %>%
filter(country %in%
c("Netherlands", "Brazil", "China", "Algeria", "New Zealand"))
recode_factor() to create the new variable. Alternatively, you could also use case_when() here. However, the latter would require more typing which is something that we generally want to avoid.